<template>
  <div class="budgetLedgerPage">
    <div class="search-wrap d-flex a-center flex-wrap">
      <div
        class="search-item d-flex a-center m-b10"
        v-if="localGet('DepartmentId') === '4342714503178637155'"
      >
        <label>部门</label>
        <el-select
          v-model="form.departmentId"
          filterable
          clearable
          class="m-l5"
          placeholder="请选择部门"
        >
          <el-option
            v-for="(item, index) in departmentList"
            :key="index"
            :label="item.deptName"
            :value="item.deptId"
          ></el-option>
        </el-select>
      </div>
      <div class="search-item d-flex a-center m-l20 m-b10">
        <label>项目名称</label>
        <el-select
          v-model="form.projectId"
          filterable
          class="m-l5"
          placeholder="请选择项目"
          clearable
        >
          <el-option
            v-for="(item, index) in projectList"
            :key="index"
            :label="item.projectName"
            :value="item.projectId"
          ></el-option>
        </el-select>
      </div>
      <div class="search-item d-flex a-center m-l20 m-b10">
        <label>年度</label>
        <el-date-picker
          class="m-l10"
          clearable
          v-model="form.year"
          value-format="YYYY"
          size="large"
          type="year"
          placeholder="请选择"
        />
      </div>
      <div class="search-item d-flex a-center m-l20 m-b10">
        <label>季度</label>
        <el-select
          v-model="form.quarter"
          class="m-l5"
          placeholder="请选择季度"
          clearable
        >
          <el-option label="一季度" value="1"></el-option>
          <el-option label="二季度" value="2"></el-option>
          <el-option label="三季度" value="3"></el-option>
          <el-option label="四季度" value="4"></el-option>
        </el-select>
      </div>
      <div class="search-item d-flex a-center m-l20 m-b10">
        <label>月度</label>
        <el-select
          v-model="form.monthly"
          class="m-l5"
          placeholder="请选择月度"
          clearable
        >
          <el-option
            v-for="i in 12"
            :label="i + '月'"
            :value="i + ''"
          ></el-option>
        </el-select>
      </div>
      <div class="search-item d-flex a-center m-l20 m-b10">
        <label>计划类型</label>
        <el-select
          v-model="form.planType"
          class="m-l5"
          placeholder="请选择计划类型"
          clearable
        >
          <el-option label="计划内" value="1"></el-option>
          <el-option label="计划外" value="2"></el-option>
        </el-select>
      </div>
      <div class="search-item d-flex a-center m-l20 m-b10">
        <label>业务单元</label>
        <el-select
          class="m-l5"
          v-model="form.businessUnitId"
          filterable
          clearable
        >
          <el-option
            v-for="(item, index) in businessUnitList"
            :key="index"
            :label="item.businessUnitName"
            :value="item.businessUnitId"
          ></el-option>
        </el-select>
      </div>
      <div class="search-item d-flex a-center m-l20 m-b10">
        <label>审核状态</label>
        <el-select class="m-l5" v-model="form.status" clearable>
          <el-option label="未提交" value="0"></el-option>
          <el-option label="审核中" value="1"></el-option>
          <el-option label="审核成功" value="2"></el-option>
          <el-option label="审核失败" value="3"></el-option>
        </el-select>
      </div>
      <div class="search-buttons m-l10 m-b10">
        <el-button color="#fc702b" style="color: #fff" @click.prevent="onQuery"
          >查询</el-button
        >
        <el-button
          color="#f0f0f0"
          style="color: #000000"
          @click.prevent="onReset"
          >重置</el-button
        >
        <el-divider direction="vertical" />
        <el-button @click="onExport" class="button_edit m-r10">
          <svg-icon
            icon-class="project-detail-icon-derive"
            class="icon-export m-r5"
          ></svg-icon>
          流入流出汇总导出
        </el-button>
        <el-button @click="onExport2" class="button_edit m-r10">
          <svg-icon
            icon-class="project-detail-icon-derive"
            class="icon-export m-r5"
          ></svg-icon>
          导出预算明细
        </el-button>
        <el-button
          class="button_edit"
          :loading="loading"
          @click="initiateProcess"
          >发起流程</el-button
        >
      </div>
    </div>
    <div class="total-warp d-flex j-end">
      <div class="m-r50">
        <span class="m-r20"
          >条数:<span class="m-l5" style="font-size: 16px; font-weight: 600">{{
            info.num
          }}</span
          >条</span
        >
        <span
          >流入金额:<span
            class="m-l5"
            style="font-size: 16px; font-weight: 600"
            >{{ info.inflowAmount }}</span
          >(元)</span
        >
        <span class="m-l20"
          >流出金额:<span
            class="m-l5"
            style="font-size: 16px; font-weight: 600"
            >{{ info.outflowAmount }}</span
          >(元)</span
        >
      </div>
    </div>
    <public-table
      ref="publicTableRef"
      class="m-t20"
      :index="false"
      radio
      border
      :page="page"
      :tableData="tableData"
      :cell-style="{ background: 'revert' }"
      :tableOption.sync="tableOption"
      :objectSpanMethod="objectSpanMethod"
      @page-change="onPageChange"
      @handleSelectionChange="handleSelectionChange"
    >
      <template #subjectName="scope">
        <el-cascader
          style="width: 100px"
          v-if="scope.row.isEdit"
          clearable
          v-model="scope.row.subjectId"
          :props="props"
        />
        <span class="m-l5">{{ scope.row.subjectName }}</span>
        <!-- <el-select v-else v-model="scope.row.subjectId">
                    <el-option v-for="(item,index) in subjectList" :key="index" :label="item.subjectName" :value="item.subjectId"></el-option>
                </el-select>-->
      </template>
      <template #budgetAmount="scope">
        <span v-if="!scope.row.isEdit">{{ scope.row.budgetAmount }}</span>
        <el-input
          v-else
          v-model="scope.row.budgetAmount"
          placeholder="请输入预算金额"
          @input="
            scope.row.budgetAmount = limitInputNum(
              scope.row.budgetAmount,
              13,
              3,
              true
            )
          "
        ></el-input>
      </template>
      <template #remarks="scope">
        <span v-if="!scope.row.isEdit">{{ scope.row.remarks || "-" }}</span>
        <el-input
          v-else
          v-model="scope.row.remarks"
          placeholder="请输入备注"
        ></el-input>
      </template>
      <template #status="scope">
        <span>{{
          ["未提交", "审批中", "审批成功", "审批失败"][scope.row.status]
        }}</span>
      </template>
      <!--            <template #update="scope">
                <el-button
                    v-if="!scope.row.isEdit && scope.row.status!==2"
                    color="#fff8f6" style="color: #fc7037;border-color: #fc7037;background-color: #fff8f6;"
                    @click="onEdit(scope.row)"
                >编辑</el-button>
                <el-button
                    v-if="scope.row.isEdit"
                    color="#fff8f6" style="color: #fc7037;border-color: #fc7037;background-color: #fff8f6;"
                    @click="onSave(scope.row)"
                >保存</el-button>
                <el-button
                    v-if="scope.row.status!==2"
                    color="#f66a6e"
                    style="color: #ffffff;"
                    @click="deleteBudget(scope.row)"
                >删除</el-button>

                <el-button
                    v-if="!scope.row.isEdit && scope.row.status===2"
                    color="#fff8f6" style="color: #fc7037;border-color: #fc7037;background-color: #fff8f6;"
                    @click="onAdjust(scope.row)"
                >调整</el-button>
            </template>-->

      <template #update="scope">
        <el-button
          v-if="isShow(scope.row.status, '编辑')"
          color="#fff8f6"
          style="
            color: #fc7037;
            border-color: #fc7037;
            background-color: #fff8f6;
          "
          @click="onEdit(scope.row)"
          >编辑</el-button
        >
        <el-button
          v-if="scope.row.isEdit"
          color="#fff8f6"
          style="
            color: #fc7037;
            border-color: #fc7037;
            background-color: #fff8f6;
          "
          @click="onSave(scope.row)"
          >保存</el-button
        >
        <el-button
          v-if="isShow(scope.row.status, '删除')"
          color="#f66a6e"
          style="color: #ffffff"
          @click="deleteBudget(scope.row)"
          >删除</el-button
        >

        <el-button
          v-if="isShow(scope.row.status, '调整')"
          color="#fff8f6"
          style="
            color: #fc7037;
            border-color: #fc7037;
            background-color: #fff8f6;
          "
          @click="onAdjust(scope.row)"
          >调整</el-button
        >
      </template>
    </public-table>
  </div>

  <adjust-popup ref="adjustPopupRef" @onSuccess="onSuccess" />
</template>

<script setup>
import {
  ElCascader,
  ElDatePicker,
  ElDivider,
  ElMessage,
  ElMessageBox,
  ElOption,
  ElSelect,
} from "element-plus";
import { onMounted, reactive, ref } from "vue";
import {
  budgetManagement,
  exportApi,
  fundManagementApi,
  otherApi,
} from "@/api/businessFinance";
import {
  exportExcelFile,
  limitInputNum,
  localGet,
  resetForm,
} from "@/common/utils/GlobalUtils";
import PublicTable from "@/components/PublicTable";
import AdjustPopup from "./components/adjustPopup.vue";

const page = reactive({
  total: 0,
  current: 1,
  size: 10,
});
const tableOption = ref([
  { label: "业务单元", prop: "businessUnitName", minWidth: 80 },
  { label: "部门", prop: "departmentName", minWidth: 80 },
  { label: "项目名称 ", prop: "projectName", minWidth: 80 },
  { label: "年度 ", prop: "year", minWidth: 80 },
  { label: "季度 ", prop: "quarter", minWidth: 80 },
  { label: "月度 ", prop: "monthly", minWidth: 80 },
  { label: "资金预算科目", prop: "subjectName", slot: true, minWidth: 120 },
  { label: "资金预算金额", prop: "budgetAmount", slot: true, minWidth: 120 },
  { label: "资金预算审核状态", prop: "status", slot: true, minWidth: 160 },
  { label: "备注", prop: "remarks", slot: true, minWidth: 80 },
  { label: "操作", prop: "update", slot: true, minWidth: 200 },
]);

const tableData = ref([]);

const form = reactive({
  departmentId: "",
  year: "",
  projectId: "",
  quarter: "",
  planType: "",
  businessUnitId: "",
  monthly: "",
  status: "",
});

/**
 * 是否显示操作按钮
 * @param status
 * @param buttonName
 */
const isShow = (status, buttonName) => {
  if (status === 1) {
    return false;
  }
  if (
    (status === 0 && buttonName === "删除") ||
    (status === 0 && buttonName === "编辑")
  ) {
    return true;
  }
  if (status === 2 && buttonName === "调整") {
    return true;
  }
  if (
    (status === 3 && buttonName === "删除") ||
    (status === 3 && buttonName === "编辑")
  ) {
    return true;
  }
  return false;
};

const departmentList = ref([]);
const getDepartmentVo = () => {
  fundManagementApi.getDepartmentVo().then((res) => {
    departmentList.value = res.data;
  });
};

const getDepartmentSummarySub = (param) => {
  fundManagementApi.getDepartmentSummarySub(param).then((res) => {
    let data = [];
    res.data.content.forEach((item, index) => {
      item.list.forEach((val) => {
        data.push({
          ...item,
          ...val,
          index,
          isEdit: false,
        });
      });
    });
    tableData.value = data;
    page.total = res.data.totalSize;
  });
};

// 合并表格
const objectSpanMethod = ({ row, column, rowIndex, columnIndex }) => {
  let data = tableData.value; //拿到当前table中数据
  let cellValue = row[column.property]; //当前位置的值
  if (columnIndex == 0 || columnIndex == 1 || columnIndex == 2) {
    let prevRow = data[rowIndex - 1]; //获取到上一条数据
    let nextRow = data[rowIndex + 1]; //下一条数据
    if (
      prevRow &&
      prevRow[column.property] === cellValue &&
      prevRow.index == row.index
    ) {
      //当有上一条数据，并且和当前值相等时
      return { rowspan: 0, colspan: 0 };
    } else {
      let countRowspan = 1;
      while (
        nextRow &&
        nextRow[column.property] === cellValue &&
        nextRow.index == row.index
      ) {
        //当有下一条数据并且和当前值相等时,获取新的下一条
        nextRow = data[++countRowspan + rowIndex];
      }
      if (countRowspan > 1) {
        return { rowspan: countRowspan, colspan: 1 };
      }
    }
  } else if (columnIndex == 4 || columnIndex == 5) {
    // if (columnIndex == 1 || columnIndex == 2) {  || columnIndex == 9
    let prevRow = data[rowIndex - 1]; //获取到上一条数据
    let nextRow = data[rowIndex + 1]; //下一条数据
    /*if (prevRow && prevRow[column.property] === cellValue && prevRow.carNum == row.carNum) { //当有上一条数据，并且和当前值相等时
            return { rowspan: 0, colspan: 0 };
        } else {
            let countRowspan = 1;
            while (nextRow && nextRow[column.property] === cellValue && nextRow.carNum == row.carNum) { //当有下一条数据并且和当前值相等时,获取新的下一条
                nextRow = data[++countRowspan + rowIndex];
            }
            if (countRowspan > 1) {
                return { rowspan: countRowspan, colspan: 1 };
            }
        }*/
    if (
      prevRow &&
      prevRow[column.property] === cellValue &&
      prevRow.carNum == row.carNum &&
      prevRow.index == row.index
    ) {
      //当有上一条数据，并且和当前值相等时
      return { rowspan: 0, colspan: 0 };
    } else {
      let countRowspan = 1;
      while (
        nextRow &&
        nextRow[column.property] === cellValue &&
        nextRow.carNum == row.carNum &&
        nextRow.index == row.index
      ) {
        //当有下一条数据并且和当前值相等时,获取新的下一条
        nextRow = data[++countRowspan + rowIndex];
      }
      if (countRowspan > 1) {
        return { rowspan: countRowspan, colspan: 1 };
      }
    }
  }
};

const onQuery = () => {
  page.current = 1;
  page.size = 10;
  let param = {
    param: {
      ...form,
    },
    pageNum: page.current,
    pageSize: page.size,
  };
  getDepartmentSummarySubTotal(form);
  getDepartmentSummarySub(param);
};

const onReset = () => {
  resetForm(form);
  page.current = 1;
  page.size = 10;
  let param = {
    pageNum: page.current,
    pageSize: page.size,
  };
  getDepartmentSummarySubTotal(form);
  getDepartmentSummarySub(param);
};

const onPageChange = (e) => {
  page.current = e.page;
  page.size = e.limit;
  let param = {
    param: {
      ...form,
    },
    pageNum: page.current,
    pageSize: page.size,
  };
  getDepartmentSummarySub(param);
};

const exportList = ref([]);
const handleSelectionChange = (e) => {
  exportList.value = e;
};

const onExport = () => {
  exportApi.getDepartmentSummarySubLeadingOut(form).then((res) => {
    if (res) {
      exportExcelFile(res, "部门资金预算台账表");
    }
  });
};
const onExport2 = () => {
  exportApi.getDepartmentSummarySubLeadingOutInfo(form).then((res) => {
    if (res) {
      exportExcelFile(res, "部门资金预算细项表");
    }
  });
};

const projectList = ref([]);
const getProjectList = () => {
  budgetManagement.getProjectList().then((res) => {
    projectList.value = res.data;
  });
};

const addInitiateProcess = (param, callback, err_callback) => {
  fundManagementApi.initiateProcess(param).then((res) => {
    if (res.code == 200) {
      if (callback) callback(res);
    } else {
      if (err_callback) err_callback(res);
    }
  });
};

const loading = ref(false);
const publicTableRef = ref(null);
const initiateProcess = () => {
  if (exportList.value.length === 0) {
    ElMessage.warning("请选择要发起流程的数据!");
    return;
  }
  loading.value = true;
  addInitiateProcess(
    exportList.value[0],
    () => {
      ElMessage.success("发起流程成功!");
      loading.value = false;
      exportList.value = [];
      publicTableRef.value.clearSelection();
    },
    () => {
      ElMessage.error("发起流程失败!");
      loading.value = false;
      exportList.value = [];
      publicTableRef.value.clearSelection();
    }
  );
};

/**
 * 开启编辑
 * @param row
 */
const onEdit = (row) => {
  row.isEdit = true;
};

const adjustPopupRef = ref(null);

/**
 * 调整
 * @param row
 */
const onAdjust = (row) => {
  let newRow = JSON.parse(JSON.stringify(row));
  delete newRow.list;
  adjustPopupRef.value.openPopup(newRow);
};

/**
 * 保存
 * @param row
 */
const onSave = (row) => {
  if (row.budgetAmount === "") {
    ElMessage.warning("请输入预算金额!");
    return;
  }
  budgetManagement
    .updateBudget({
      budgetPlanId: row.budgetPlanId,
      subjectId: Array.isArray(row.subjectId)
        ? row.subjectId[row.subjectId.length - 1]
        : row.subjectId,
      budgetAmount: row.budgetAmount,
      remarks: row.remarks,
    })
    .then((res) => {
      if (res.code === "200") {
        row.isEdit = false;
        ElMessage.success("编辑成功");
        let param = {
          param: {
            ...form,
          },
          pageNum: page.current,
          pageSize: page.size,
        };
        getDepartmentSummarySubTotal(form);
        getDepartmentSummarySub(param);
      }
    });
};

/**
 * 删除资金预算
 * @param row
 */
const deleteBudget = (row) => {
  ElMessageBox.alert("确认删除吗?", "提示", {
    showCancelButton: true,
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    callback: (action) => {
      if (action === "confirm") {
        budgetManagement.deleteBudget(row.budgetPlanId).then((res) => {
          ElMessage.success("删除成功!");
          getDepartmentSummarySub({
            pageNum: 1,
            pageSize: 10,
          });
          getDepartmentSummarySubTotal(form);
        });
      }
    },
  });
};

/**
 * 查询五级科目
 */
const subjectList = ref([]);
const getWuBudgetSubject = () => {
  otherApi.getWuBudgetSubject().then((res) => {
    if (res.code === "200") {
      subjectList.value = res.data;
    }
  });
};

/**
 * 获取业务单元
 */
const businessUnitList = ref([]);
const getFundBudgetBusinessUnitAll = () => {
  fundManagementApi.getFundBudgetBusinessUnitAll().then((res) => {
    if (res.code === "200") {
      businessUnitList.value = res.data;
    }
  });
};

/**
 * 资金预算台账按搜索条件-统计
 * @param params
 */
const info = reactive({
  num: 0,
  amount: 0,
});
const getDepartmentSummarySubTotal = (params) => {
  fundManagementApi.getDepartmentSummarySubTotal(params).then((res) => {
    if (res.code === "200") {
      info.num = res.data.num;
      info.inflowAmount = res.data.inflowAmount;
      info.outflowAmount = res.data.outflowAmount;
    }
  });
};

const props = {
  lazy: true,
  async lazyLoad(node, resolve) {
    const { level } = node;
    if (level === 0) {
      const res = await fundManagementApi.getBudgetSubjectList({
        subjectId: "",
        subjectType: "1",
      });
      let nodes = [];
      res.data.forEach((item) => {
        nodes.push({
          value: item.subjectId,
          label: item.subjectName,
          leaf: level >= 4,
        });
      });
      resolve(nodes);
    }
    if (level > 0 && level === 5) {
      resolve([]);
    }
    if (level > 0 && level < 5) {
      const res = await fundManagementApi.getBudgetSubjectList({
        subjectId: node.value,
        subjectType: "1",
      });
      let nodes = [];
      res.data.forEach((item) => {
        nodes.push({
          value: item.subjectId,
          label: item.subjectName,
          leaf: level >= 4,
        });
      });
      resolve(nodes);
    }
  },
};

const onSuccess = () => {
  onQuery();
};

onMounted(() => {
  getDepartmentVo();
  getProjectList();
  getWuBudgetSubject();
  getFundBudgetBusinessUnitAll();
  getDepartmentSummarySub({
    pageNum: 1,
    pageSize: 10,
  });
  getDepartmentSummarySubTotal(form);
});
</script>

<style lang="scss" scoped>
.buttons-row {
  width: 100%;
  span {
    font-size: 15px;
    font-weight: 600;
  }
  .buttons-box {
    .icon {
      cursor: pointer;
      width: 28px;
      height: 28px;
    }
  }
}
.budgetLedgerPage {
  .search-wrap {
    .search-item {
      .el-input {
        width: auto !important;
      }
    }
    .search-buttons {
      .icon-export {
        width: 18px;
        height: 18px;
      }
    }
  }
}
</style>
